package zyh.servlet;

import zyh.servlet.DbDao;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;

@WebServlet(name = "LoginServlet",urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
    public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException,java.io.IOException{
        String errMsg="";
        RequestDispatcher rd;
        String username=request.getParameter("username");
        String pass=request.getParameter("pass");
        try
        {
            DbDao dd=new DbDao("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/1613580003",
                    "root","123456");
            ResultSet rs=dd.query("select pass from t_users"+" where name = ?",username);
            if(rs.next())
            {
                if(rs.getString("pass").equals(pass))
                {
                    HttpSession session= (HttpSession) request.getSession(true);
                    session.setAttribute("name",username);
                    rd=request.getRequestDispatcher("/fs");
                    rd.forward(request,response);
                }
                else
                {
                    errMsg +="您的用户名密码不符合，请重新输入";
                }
            }
            else
            {
                errMsg +="您的用户名不存在，请先注册";
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        if(errMsg !=null && !errMsg.equals(""))
        {
            rd=request.getRequestDispatcher("/login");
            request.setAttribute("err",errMsg );
            rd.forward(request,response);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
